<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="SQL server中完整性约束及触发器">
<meta name="keywords" content="学习笔记,SQL server">
<meta property="og:type" content="article">
<meta property="og:title" content="SQL server中的完整性及触发器">
<meta property="og:url" content="https:&#x2F;&#x2F;fwj1635387072.github.io&#x2F;2019&#x2F;11&#x2F;12&#x2F;%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AE%8C%E6%95%B4%E6%80%A7&#x2F;index.html">
<meta property="og:site_name" content="付文杰的博客">
<meta property="og:description" content="SQL server中完整性约束及触发器">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-11-12T15:46:03.439Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://fwj1635387072.github.io/2019/11/12/%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AE%8C%E6%95%B4%E6%80%A7/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>


  <title>SQL server中的完整性及触发器 | 付文杰的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">付文杰的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">个人博客  |  日常</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>

      </div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://FWj1635387072.github.io/2019/11/12/%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AE%8C%E6%95%B4%E6%80%A7/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/headImage.jpg">
      <meta itemprop="name" content="付文杰">
      <meta itemprop="description" content="兰州交通大学 | 本科生 <br> 信息管理与信息系统">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="付文杰的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          SQL server中的完整性及触发器
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2019-11-12 23:26:33 / 修改时间：23:46:03" itemprop="dateCreated datePublished" datetime="2019-11-12T23:26:33+08:00">2019-11-12</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.7k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>6 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>SQL server中完整性约束及触发器</p>
<a id="more"></a>

<p>数据库完整性指数据的正确性和相容性</p>
<p>​    正确：数据是符合现实世界语义、反应当前实际状况</p>
<p>​    相容：数据库同一对象在不同关系表中的数据是符合逻辑的</p>
<h2 id="实体完整性"><a href="#实体完整性" class="headerlink" title="实体完整性"></a>实体完整性</h2><p>实体完整性有primary key定义，包括列级和表级完整性。</p>
<p>保证主键唯一、非空    </p>
<p>当用户对基本表插入一条记录或者对主码列进行更行时，RDBMS将自动对实体完整性进行检查：        </p>
<p>​    1、检查主码是否唯一，如果不唯一则拒绝插入和修改</p>
<p>​    2、检查主码的各个属性是否为空，只要有一个为空则拒绝插入和修改</p>
<p>检查主码值是否唯一的一种方法是进行全表扫描，依次判断表中的每一条记录的主码值是否与插入记录的主</p>
<p>码一致</p>
<p>全表扫描很费时，为避免进行全表扫描，RDBMS一般都在主码上自动建立一个索引，如下图的B+树，通过索引查找可大大提高效率    </p>
<h2 id="参照完整性"><a href="#参照完整性" class="headerlink" title="参照完整性"></a>参照完整性</h2><p>参照完整性用foreign key进行定义，用references表示参考哪一个表的哪一个属性</p>
<table>
<thead>
<tr>
<th align="center">被参照表（student）</th>
<th align="center">参照表（sc）</th>
<th align="center">违约处理</th>
</tr>
</thead>
<tbody><tr>
<td align="center"></td>
<td align="center">插入元组</td>
<td align="center">拒绝</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">修改外码值</td>
<td align="center">拒绝</td>
</tr>
<tr>
<td align="center">删除元组</td>
<td align="center"></td>
<td align="center">拒绝/级联/设置为空/设置为默认值</td>
</tr>
<tr>
<td align="center">修改主码值</td>
<td align="center"></td>
<td align="center">拒绝/级联/设置为空/设置为默认值</td>
</tr>
</tbody></table>
<ol>
<li><p>向sc中插入元组，如果不满足参照完整性，拒绝执行</p>
</li>
<li><p>修改sc的外码值，如果不满足参照完整性，拒绝执行</p>
</li>
<li><p>删除student表中的元组，如果sc中的数据不满足参照完整性，则执行拒绝/级联/设置为空/设置为默认值，由用户定义</p>
</li>
<li><p>修改student表中的主码值，导致sc中的数据不满足参照完整性，则执行拒绝/级联/设置为空/设置为默认值，由用户定义</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--当对student表中的sno进行删除时，级联删除sc表中的数据</span></span><br><span class="line"><span class="comment">--对sno进行修改时，级联更新sc表中的数据</span></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> sc</span><br><span class="line"><span class="keyword">add</span> <span class="keyword">constraint</span> FK_student_sno 			<span class="comment">--外键（约束）命名</span></span><br><span class="line"><span class="keyword">foreign</span> <span class="keyword">key</span>(sno) <span class="keyword">references</span> student(sno)	<span class="comment">--定义外键</span></span><br><span class="line"><span class="keyword">on</span> <span class="keyword">delete</span> <span class="keyword">cascade</span>			<span class="comment">--级联删除</span></span><br><span class="line"><span class="keyword">on</span> <span class="keyword">update</span> <span class="keyword">cascade</span>			<span class="comment">--级联更新</span></span><br><span class="line"></span><br><span class="line"><span class="comment">--对course表中的cno进行删除时，拒绝执行</span></span><br><span class="line"><span class="comment">--对cno进行修改时，级联修改</span></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> sc</span><br><span class="line"><span class="keyword">add</span> <span class="keyword">constraint</span> FK_course_cno</span><br><span class="line"><span class="keyword">foreign</span> <span class="keyword">key</span>(cno) <span class="keyword">references</span> course(cno)</span><br><span class="line"><span class="keyword">on</span> <span class="keyword">delete</span> <span class="keyword">no</span> <span class="keyword">action</span></span><br><span class="line"><span class="keyword">on</span> <span class="keyword">update</span> <span class="keyword">cascade</span></span><br><span class="line"></span><br><span class="line"><span class="comment">--sql server中还支持set null和set default</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> t1(</span><br><span class="line">	a <span class="built_in">int</span> primary <span class="keyword">key</span></span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> t2</span><br><span class="line">(</span><br><span class="line">	a1 <span class="built_in">int</span>,</span><br><span class="line">b1 <span class="built_in">int</span> <span class="keyword">default</span>(<span class="number">20</span>)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> t3</span><br><span class="line">(</span><br><span class="line">	b <span class="built_in">int</span> primary <span class="keyword">key</span></span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="comment">--给t2增加名为FK_t1_a的外键，参考t1中的a</span></span><br><span class="line"><span class="comment">--给</span></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> t2 </span><br><span class="line"><span class="keyword">add</span> <span class="keyword">constraint</span> FK_t1_a</span><br><span class="line"><span class="keyword">foreign</span> <span class="keyword">key</span>(a1) <span class="keyword">references</span> t1(a)</span><br><span class="line"><span class="keyword">on</span> <span class="keyword">delete</span> <span class="keyword">set</span> <span class="literal">null</span>,  <span class="comment">--两个外键的分界</span></span><br><span class="line"><span class="keyword">constraint</span> FK_t1_b		<span class="comment">--外键命名</span></span><br><span class="line"><span class="keyword">foreign</span> <span class="keyword">key</span>(b1) <span class="keyword">references</span> t3(b)</span><br><span class="line"><span class="keyword">on</span> <span class="keyword">update</span> <span class="keyword">set</span> <span class="keyword">default</span></span><br><span class="line"></span><br><span class="line"><span class="comment">--向t1，t2，t3表中添加数据，并验证修改t3表，t2表中数据是否改变</span></span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> t1 <span class="keyword">values</span>(<span class="number">1</span>)</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> t3 <span class="keyword">values</span>(<span class="number">2</span>)</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> t2 <span class="keyword">values</span>(<span class="number">1</span>,<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">update</span> t3 <span class="keyword">set</span> b = <span class="number">10</span> <span class="keyword">where</span> b = <span class="number">2</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> t2</span><br><span class="line"><span class="comment">--可以看到t2表中的b1变为20</span></span><br><span class="line"><span class="keyword">delete</span> <span class="keyword">from</span> t1</span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> t2</span><br><span class="line"><span class="comment">--可以看到t2表中的a1变为了null</span></span><br></pre></td></tr></table></figure>

<p>注意：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--注意外键引用，如果被参考的属性为主码，那么主码中有几个属性，定义参考时就要有几个属性</span></span><br><span class="line"><span class="comment">--例子：</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tt1(</span><br><span class="line">	a <span class="built_in">int</span>,</span><br><span class="line">	b <span class="built_in">int</span>,</span><br><span class="line">	c <span class="built_in">int</span>,</span><br><span class="line">	primary <span class="keyword">key</span>(a,b)</span><br><span class="line">)</span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tt2(</span><br><span class="line">	a <span class="built_in">int</span> ,</span><br><span class="line">	b <span class="built_in">int</span> ,</span><br><span class="line"><span class="keyword">foreign</span> <span class="keyword">key</span>(a,b) <span class="keyword">references</span> tt1(a,b)</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">--错误示范：</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tt1(</span><br><span class="line">  a <span class="built_in">int</span>,</span><br><span class="line">  b <span class="built_in">int</span>,</span><br><span class="line">  c <span class="built_in">int</span>,</span><br><span class="line">  primary <span class="keyword">key</span>(a,b)</span><br><span class="line">)</span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tt2(</span><br><span class="line">  a <span class="built_in">int</span> ,</span><br><span class="line">  b <span class="built_in">int</span> ,</span><br><span class="line">	<span class="keyword">foreign</span> <span class="keyword">key</span>(a）<span class="keyword">references</span> tt1(a),</span><br><span class="line">  <span class="keyword">foreign</span> <span class="keyword">key</span>(a) <span class="keyword">references</span> tt1(b)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h2 id="触发器"><a href="#触发器" class="headerlink" title="触发器"></a>触发器</h2><p>触发器是用户定义在关系表（基本表）上的一类由<strong>事件</strong>驱动的特殊过程</p>
<p>就本质而言，触发器也是一种存储过程，它在特定语言事件发生时自动执行</p>
<p>触发器保存在数据库服务器上，与约束类似，但比约束灵活，可用来进行更复杂的检查和操作</p>
<p>触发器的使用过程：定义、激活、删除</p>
<h3 id="SQL-server中触发器（主要为DML触发器）"><a href="#SQL-server中触发器（主要为DML触发器）" class="headerlink" title="SQL server中触发器（主要为DML触发器）"></a>SQL server中触发器（主要为DML触发器）</h3><h4 id="After触发器"><a href="#After触发器" class="headerlink" title="After触发器"></a>After触发器</h4><p>​    触发事件执行完激活执行，主要用于记录变更后的检查或处理。</p>
<p>​    删除：SQL server 遇到delete语句，将要删的元组放到一个临时表（deleted）中，然后删除数据表中数据，执行触发事件，然后删掉临时表。</p>
<p>​    修改：SQL server遇到update语句，将要修改的元组放到一个临时表（inserted）中，修改后的元组放到另一个临时表（deleted）中，然后修改数据表中的数据，执行触发事件，最后删掉临时表（inserted、deleted）</p>
<p>​    增加与上面过程类似，不再赘叙。</p>
<h4 id="Instead-of触发器"><a href="#Instead-of触发器" class="headerlink" title="Instead of触发器"></a>Instead of触发器</h4><p>​    触发事件执行前激活执行</p>
<p>​    与After触发器的区别在于：<br>​        它不执行原来sql中的操作，而是执行触发事件中的sql语句</p>
<p>一般触发器不能作用在视图上，但是sql server中触发器可以作用在视图上。</p>
<h4 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h4><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">trigger</span> [ schema_name . ]trigger_name </span><br><span class="line"><span class="keyword">ON</span> &#123; <span class="keyword">table</span> | <span class="keyword">view</span> &#125; </span><br><span class="line">&#123; <span class="keyword">FOR</span> | <span class="keyword">AFTER</span> | INSTEAD <span class="keyword">OF</span> &#125; 				<span class="comment">--for after代表都是after触发器</span></span><br><span class="line">&#123; [ <span class="keyword">INSERT</span> ] [ , ] [ <span class="keyword">UPDATE</span> ] [ , ] [ <span class="keyword">DELETE</span> ] &#125; </span><br><span class="line"><span class="keyword">AS</span> &#123; sql_statement  [ ; ]</span><br><span class="line"></span><br><span class="line"><span class="comment">--例子1：在插入一个学生后，查询全部学生</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> student (</span><br><span class="line">	sno <span class="built_in">varchar</span>(<span class="number">10</span>),</span><br><span class="line">	sname <span class="built_in">varchar</span>(<span class="number">20</span>),</span><br><span class="line">	sage <span class="built_in">int</span>,</span><br><span class="line">)</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> student <span class="keyword">values</span>(<span class="string">'0001'</span>,<span class="string">'aaa'</span>,<span class="number">19</span>),</span><br><span class="line">						(<span class="string">'0002'</span>,<span class="string">'bbb'</span>,<span class="number">20</span>),(<span class="string">'0003'</span>,<span class="string">'ccc'</span>,<span class="number">21</span>)</span><br><span class="line"><span class="comment">--以上为创建基本对象</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">trigger</span> t1		<span class="comment">--创建触发器</span></span><br><span class="line"><span class="keyword">on</span> student <span class="keyword">after</span> <span class="keyword">insert</span>		<span class="comment">--在学生表上定义after触发器，在insert语句后执行</span></span><br><span class="line"><span class="keyword">as</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> student		<span class="comment">--触发后执行的语句</span></span><br><span class="line"></span><br><span class="line"><span class="comment">--测试</span></span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> student <span class="keyword">values</span>(<span class="string">'0004'</span>,<span class="string">'ddd'</span>,<span class="number">22</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">--例子2：对sc表中的成绩进行修改时，如果分数增加10%，</span></span><br><span class="line"><span class="comment">--则将次操作记录到另一个表SC_U(sno、cno、oldGrade、newGrade)</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> sc</span><br><span class="line">(</span><br><span class="line">  sno <span class="built_in">varchar</span>(<span class="number">10</span>),</span><br><span class="line"> 	cno <span class="built_in">varchar</span>(<span class="number">10</span>),</span><br><span class="line">  grade <span class="built_in">int</span></span><br><span class="line">)</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> sc <span class="keyword">values</span>(<span class="number">1</span>,<span class="number">1</span>,<span class="number">90</span>),</span><br><span class="line">						(<span class="number">1</span>,<span class="number">2</span>,<span class="number">80</span>),</span><br><span class="line">						(<span class="number">1</span>,<span class="number">3</span>,<span class="number">70</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> sc_u(</span><br><span class="line">	sno <span class="built_in">varchar</span>(<span class="number">10</span>),</span><br><span class="line">	cno <span class="built_in">varchar</span>(<span class="number">10</span>),</span><br><span class="line">	oldGrade <span class="built_in">int</span>,</span><br><span class="line">	newGrade <span class="built_in">int</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">-------------以下创建After触发器</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">trigger</span> t2		<span class="comment">--定义触发器的名称</span></span><br><span class="line"><span class="keyword">on</span> sc <span class="keyword">after</span> <span class="keyword">update</span>		<span class="comment">--在那个表上，触发类型</span></span><br><span class="line"><span class="keyword">as</span>			</span><br><span class="line"><span class="keyword">begin</span></span><br><span class="line">	<span class="keyword">declare</span> @<span class="keyword">old</span> <span class="built_in">int</span>,@<span class="keyword">new</span> <span class="built_in">int</span>,@sno <span class="built_in">varchar</span>(<span class="number">10</span>),@cno <span class="built_in">varchar</span>(<span class="number">10</span>)<span class="comment">--定义局部变量</span></span><br><span class="line">	<span class="keyword">set</span> @<span class="keyword">old</span> = (<span class="keyword">select</span> grade <span class="keyword">from</span> deleted)		<span class="comment">--为定义的变量设置值</span></span><br><span class="line">	<span class="keyword">set</span> @<span class="keyword">new</span> = (<span class="keyword">select</span> grade <span class="keyword">from</span> inserted)</span><br><span class="line">	<span class="keyword">set</span> @sno = (<span class="keyword">select</span> sno <span class="keyword">from</span> deleted)</span><br><span class="line">	<span class="keyword">set</span> @cno = (<span class="keyword">select</span> cno <span class="keyword">from</span> deleted)</span><br><span class="line">	<span class="keyword">if</span> @<span class="keyword">new</span> &gt;= <span class="number">1.1</span> * @<span class="keyword">old</span>			<span class="comment">--进行判断，然后执行语句</span></span><br><span class="line">		<span class="keyword">insert</span> <span class="keyword">into</span> sc_u <span class="keyword">values</span>(@sno,@cno,@<span class="keyword">old</span>,@<span class="keyword">new</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">--测试</span></span><br><span class="line"><span class="keyword">update</span> sc <span class="keyword">set</span> grade = <span class="number">1.2</span> * grade <span class="keyword">where</span> cno = <span class="number">2</span></span><br></pre></td></tr></table></figure>

</li>
</ol>

    </div>

    
    
    

      
      <div>
        
          <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
        
      </div>

      <footer class="post-footer">



        
<div>    
 
 
<ul class="post-copyright">
  <li class="post-copyright-author">
      <strong>本文作者：</strong>付文杰
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="/2019/11/12/%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AE%8C%E6%95%B4%E6%80%A7/" title="SQL server中的完整性及触发器">2019/11/12/数据库完整性/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权： </strong>
    本站文章均采用 <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/cn/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0 CN</a> 许可协议，请勿用于商业，转载注明出处！
  </li>
</ul>

</div>
          <div class="post-tags">
              <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"><i class="fa fa-tag"></i> 学习笔记</a>
              <a href="/tags/SQL-server/" rel="tag"><i class="fa fa-tag"></i> SQL server</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
                <a href="/2019/11/10/%E5%8D%95%E9%93%BE%E8%A1%A8/" rel="next" title="数据结构中的单链表（Java语言）">
                  <i class="fa fa-chevron-left"></i> 数据结构中的单链表（Java语言）
                </a>
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
                <a href="/2019/11/14/%E5%8F%8C%E9%93%BE%E8%A1%A8/" rel="prev" title="数据结构中的双链表以及链表的一个使用实例（Java语言）">
                  数据结构中的双链表以及链表的一个使用实例（Java语言） <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
    <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=27588222&auto=1&height=66"></iframe>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#实体完整性"><span class="nav-number">1.</span> <span class="nav-text">实体完整性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参照完整性"><span class="nav-number">2.</span> <span class="nav-text">参照完整性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#触发器"><span class="nav-number">3.</span> <span class="nav-text">触发器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#SQL-server中触发器（主要为DML触发器）"><span class="nav-number">3.1.</span> <span class="nav-text">SQL server中触发器（主要为DML触发器）</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#After触发器"><span class="nav-number">3.1.1.</span> <span class="nav-text">After触发器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Instead-of触发器"><span class="nav-number">3.1.2.</span> <span class="nav-text">Instead of触发器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#语法"><span class="nav-number">3.1.3.</span> <span class="nav-text">语法</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <img class="site-author-image" itemprop="image" alt="付文杰"
    src="/images/headImage.jpg">
  <p class="site-author-name" itemprop="name">付文杰</p>
  <div class="site-description" itemprop="description">兰州交通大学 | 本科生 <br> 信息管理与信息系统</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">63</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/FWj1635387072" title="GitHub &amp;rarr; https:&#x2F;&#x2F;github.com&#x2F;FWj1635387072" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/mailto:1635387072@qq.com" title="E-Mail &amp;rarr; mailto:1635387072@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/null" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>





      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        


<div class="copyright">
  
  &copy; 2019 – 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">付文杰</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">210k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">5:50</span>

  <br>
  <span id="sitetime"></span>

</div>
<script language=javascript>
    function siteTime() {
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth() + 1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */
        var t1 = Date.UTC(2019, 11, 7, 17, 50, 00); //北京时间2018-2-13 00:00:00
        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
        var diff = t2 - t1;
        var diffYears = Math.floor(diff / years);
        var diffDays = Math.floor((diff / days) - diffYears * 365);
        var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
        var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) / minutes);
        var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours - diffMinutes * minutes) / seconds);
        document.getElementById("sitetime").innerHTML = "本站已运行 " +diffYears+" 年 "+diffDays + " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
    }/*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
    siteTime();
</script>


        












        
      </div>
    </footer>
  </div>

  
  
  <script color='0,0,255' opacity='0.5' zIndex='-1' count='99' src="/lib/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/pisces.js"></script>
<script src="/js/next-boot.js"></script>



  
















  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/live2dw/assets/wanko.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":false},"symbols_count_time":null,"symbols":true,"time":true,"total_symbols":true,"total_time":true,"log":false});</script></body>
</html>
<script type="text/javascript" src="/js/src/clicklove.js"></script>